#!/bin/bash
# shellcheck disable=SC2068
# shellcheck disable=SC2164
# shellcheck disable=SC2002
# shellcheck disable=SC2045
# shellcheck disable=SC2115
rpm_name=$1
remote_branch=$2
patch_path=$3
source_path=$4
current_path=$(
  cd "$(dirname "$0")"
  pwd
)
. ${current_path}/common.sh

function check() {
  # Check input legitimacy
  if [[ -z ${rpm_name} ]] || [[ -z ${remote_branch} ]]; then
    echo "[ERROR] rpm name or gitee branch not specified"
    exit 1
  fi
  # Check if the path exists
  if [[ ! -d ${patch_path} ]] || [[ ! -d ${source_path} ]]; then
    echo "[ERROR] The patch file directory: ${patch_path} or the source code download directory: ${source_path} does not exist is not exist"
    exit 1
  fi
}

function run() {
  patch_files=$(ls ${patch_path})
  patch_ids=""
  new_patches=""
  for patch_file in ${patch_files[@]}; do
    patch_file=${patch_path}/${patch_file}
    git_patch_ids=$(cat "${patch_file}" | git patch-id --stable)
    if [[ ! ${patch_ids} =~ ${git_patch_ids} ]]; then
      new_patches="${new_patches} ${patch_file}"
      patch_ids="${patch_ids} ${git_patch_ids}"
    else
      echo "[INFO] ${patch_file} duplicate content"
    fi
  done
  # Perform code download, modify spec file, package verification operation
  /bin/bash ${current_path}/packing.sh "${rpm_name}" "${remote_branch}" "${new_patches}" "${source_path}"
  add_patch_result=$?
  if [[ ${add_patch_result} -eq 0 ]]; then
    echo "[INFO] rpm: \"${rpm_name}\" of branch: \"${remote_branch}\" apply patch \"${new_patches}\" successfully"
    exit 0
  else
    echo "[ERROR] rpm: \"${rpm_name}\" of branch: \"${remote_branch}\" failed to apply patch \"${new_patches}\""
    exit 1
  fi
}

function main() {
  # Executive total entrance
  check
  install_rpm git git
  run
}

main
